#include <assert.h>
#include <QtGui>

#include "WidgetGroup.h"

#include "SubFrame.h"

WidgetGroup::WidgetGroup(QMainWindow* pParent, const QString& name):
	QObject(pParent),
	m_pWidgetStack(new QStackedWidget(pParent)),
	m_pActionGroup(new QActionGroup(pParent)),
	m_pToolBar(new QToolBar(name, pParent))
{
	m_pToolBar->setIconSize(QSize(48, 48));
	m_pToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
	pParent->addToolBar(Qt::LeftToolBarArea, m_pToolBar);

	connect(m_pActionGroup, SIGNAL(triggered(QAction *)), this, SLOT(ActionClicked(QAction *)));

	pParent->setCentralWidget(m_pWidgetStack);
}

void WidgetGroup::ActionClicked(QAction * action)
{
	WidgetMap::Iterator it = m_widgetMap.find(action);
	if(m_widgetMap.end() == it)
	{
		return;
	}

	SubFrame* pSF =  (SubFrame*)it.value();
	pSF->active();

	m_pWidgetStack->setCurrentWidget(it.value());
	QWidget* pParent = (QWidget*)parent();
	QString str = action->iconText();
	pParent->setWindowTitle(m_pToolBar->windowTitle() + "--" + action->iconText());
}

WidgetGroup::~WidgetGroup(void)
{

}

void WidgetGroup::SetCurrentWidget(QWidget* pWidget)
{
	WidgetMap::Iterator it = m_widgetMap.begin();
	while(m_widgetMap.end() != it)
	{
		if(it.value() == pWidget)
		{
			((QAction*)(it.key()))->trigger();
			break;;
		}
		++it;
	}
}

SubFrame* WidgetGroup::CurrentWidget()
{
	return (SubFrame*)(m_pWidgetStack->currentWidget());
}

QStackedWidget* WidgetGroup::StackedWidget()
{
	return m_pWidgetStack;
}

void WidgetGroup::AddChild(const QString& iconName, const QString& label, SubFrame* pFrame)
{
	QMainWindow* pParent = (QMainWindow*)parent();
	QAction* action = new QAction(QIcon(iconName), label, pParent);
	action->setCheckable(true);

	m_pToolBar->addAction(action);
	m_pActionGroup->addAction(action);
	m_pWidgetStack->addWidget(pFrame);
	m_widgetMap.insert(action, pFrame);
}